<?php
namespace exportExcel;

class ExportExcel{

    /*
    *处理Excel导出入口
    *@param $title string 设置表名
    *@param $key string 设置表头
    *@param $data array 设置表格数据
    *@param $filename string 设置文件名
    */

    public function index($params){
        $title= "<tr><th>{$params['title']}</th></tr>";
        $key = $params['key'];
        $str = "<tr>";
        foreach($key as $k=>$v){
            $str .= "<th>$v</th>";
        }
        $str  .= "</tr>";
        $key = $str;
        $data = $params['data'];
        $filename = $params['filename'];
        $this->excelData($data,$title,$key,$filename);
    }


    public function excelData($datas,$titlename,$title,$filename){
        $str = "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\nxmlns:x=\"urn:schemas-microsoft-com:office:excel\"\r\nxmlns=\"http://www.w3.org/TR/REC-html40\">\r\n<head>\r\n<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">\r\n</head>\r\n<body>";
        $str .="<table border=1><head>".$titlename."</head>";
        $str .= $title;
        foreach ($datas  as $key=> $rt )
        {
            $str .= "<tr>";
            foreach ( $rt as $k => $v )
            {
                $str .= "<td>{$v}</td>";
            }
            $str .= "</tr>\n";
        }
        $str .= "</table></body></html>";
        header( "Content-Type: application/vnd.ms-excel; name='excel'" );
        header( "Content-type: application/octet-stream" );
        header( "Content-Disposition: attachment; filename=".$filename );
        header( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
        header( "Pragma: no-cache" );
        header( "Expires: 0" );
        exit( $str );
    }
}


